<template>
  <Card title="映射字段" :head-style="{ textAlign: 'center', fontWeight: 'bold' }">
    <Table :data-source="list" :columns="columns" :pagination="false" :showHeader="false">
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex == 'sourceField'">
          <Select
            style="width: 160px"
            :options="formGetFieldsDataWithId"
            v-model:value="record[column.dataIndex]"
            :field-names="{ label: 'title', value: 'name' }"
            :get-popup-container="getPopupContainer"
            :disabled="index != 0"
            show-search
            optionFilterProp="title"
            @change="setName($event, record, 'sourceFieldName', formGetFieldsData)"
          />
        </template>
        <template v-if="column.dataIndex == 'destField'">
          <Select
            style="width: 160px"
            :options="formGetFieldsDataTo"
            v-model:value="record[column.dataIndex]"
            :get-popup-container="getPopupContainer"
            :field-names="{ label: 'title', value: 'name' }"
            :disabled="index != 0"
            show-search
            optionFilterProp="title"
            @change="setName($event, record, 'destFieldName', formGetFieldsDataTo)"
          />
        </template>
        <template v-if="column.dataIndex == 'cz'">
          <a-button v-if="index == 0" @click="handleCreate(record)">添加</a-button>
          <a-button v-else @click="handleDelete(index)">删除</a-button>
        </template>
      </template>
    </Table>
  </Card>
</template>
<script lang="ts" setup>
  import { ref, watch, onMounted } from 'vue';
  import { Card, Table, Select, message } from 'ant-design-vue';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { isArray } from '/@/utils/is';
  import { useRouter } from 'vue-router';
  import { deepClone } from '/@/views/formDesigner/utils';

  const { currentRoute } = useRouter();
  const emit = defineEmits(['update:modelValue']);
  const props = defineProps({
    formGetFieldsData: {
      type: Array,
      default: () => [],
    },
    modelValue: {
      type: Array,
      default: () => [],
    },
  });

  const columns = [
    {
      dataIndex: 'name',
      title: '映射',
      align: 'center',
    },
    {
      dataIndex: 'sourceField',
      title: '来源',
      align: 'center',
    },
    {
      dataIndex: 'destField',
      title: '目标',
      align: 'center',
    },
    {
      dataIndex: 'cz',
      title: '操作',
      align: 'center',
    },
  ];
  const obj = {
    name: '映射',
    sourceField: '',
    sourceFieldName: '',
    destField: '',
    destFieldName: '',
  };
  const list = ref([{}]);

  watch(
    () => props.modelValue,
    (newVal) => {
      list.value = newVal as Recordable[];
      console.log('list.value', list.value);
    },
    {
      immediate: true,
    },
  );
  const handleCreate = (record) => {
    if (!record.sourceField || !record.destField) {
      message.warning('请选择表单域');
      return;
    }
    const newObj = { ...obj };
    list.value.unshift(newObj);
    setEmit();
  };

  const handleDelete = (index) => {
    list.value.splice(index, 1);
  };

  const setEmit = () => {
    emit('update:modelValue', list.value);
  };
  const setName = (val, record, col, data) => {
    if (!val) return;
    record[col] = data.find((item) => item.name == val)?.title;
  };
  const handleInit = () => {
    list.value = [{ ...obj }];
    setEmit();
  };

  const formGetFieldsDataTo = ref<Recordable[]>([]);
  //获取目标字段
  const getFormGetFieldsDataTo = () => {
    try {
      const { query } = currentRoute.value;
      if (query?.formCode) {
        getFormGetFields({ formCode: query.formCode }).then((res) => {
          formGetFieldsDataTo.value = res || [];
          if (isArray(formGetFieldsDataTo.value)) {
            formGetFieldsDataTo.value.forEach((item) => {
              item.label = item.title;
              item.value = item.name;
              delete item.options;
            });
          }
        });
      }
    } catch (err) {
      console.log('getFormGetFields', err);
    }
  };

  const formGetFieldsDataWithId = ref<Recordable[]>([]);
  onMounted(() => {
    console.log('props.formGetFieldsData', props.formGetFieldsData);
    formGetFieldsDataWithId.value = deepClone(props.formGetFieldsData);
    formGetFieldsDataWithId.value.push({
      code: 'id',
      name: 'ID',
    });

    getFormGetFieldsDataTo();
  });

  watch(
    () => props.formGetFieldsData,
    (newVal) => {
      formGetFieldsDataWithId.value = deepClone(newVal as Recordable[]);
      formGetFieldsDataWithId.value.push({
        code: 'id',
        name: 'ID',
      });
      console.log('formGetFieldsDataWithId', formGetFieldsDataWithId.value);
    },
    {
      immediate: true,
    },
  );

  const getPopupContainer = (triggerNode) => triggerNode?.parentNode;

  defineExpose({
    handleInit,
  });
</script>
